<template>
  <a-drawer
      title="拆分账单"
      :maskClosable="false"
      :visible="visible"
      width="600"
      :body-style="{
      paddingBottom: '80px',
      height: 'calc(100% - 110px)',
      boxSizing: 'border-box',
      overflowY: 'auto',
    }"
      @close="onCancel"
  >
    <div>
      <a-alert type="info" v-if="!splitApprove" style="margin-bottom: 10px">
        <template #message>
          账单拆分暂未开启审批，点击”
          <span v-if="splitis_admin" class="link" @click.stop="goSetting(split_id, 1)">配置</span>
          <span v-else class="link" style="cursor: not-allowed">配置</span>
          “可快速设置。
        </template>
      </a-alert>

      <div class="prompt">
        <div style="padding-bottom: 10px;">
          拆分账单审批通过后生成新的账单，被拆分的老账单自动关闭。被拆分的老账单如果是合同账单，被拆分后生成的新账单仍然归属于原合同账单
        </div>
        <div>拆分订单后的订单总金额不能小于原始订单金额</div>
      </div>

      <div class="Billinformation">
        <div class="mb-5">账单类型：{{ content.cost_type_txt }}</div>
        <div class="mb-5">账单金额：￥{{ content.bill_amount }}</div>
        <div class="mb-5">计费周期：{{ content.start_date }}~{{ content.end_date }}</div>
        <!--        （{{content.diff_month}}个月）-->
        <div v-if="content.latefee_amount > 0" class="mb-5">滞纳金：{{ content.latefee_amount }}
        </div>
      </div>

      <div class="mb-30" style="position: relative;">
        <div class="mb-5">
          <span style="color: red;">*</span>拆分后付款周期（几月一付）
          <a-tooltip>
            <template #title>按照起始日划分</template>
            <question-circle-outlined/>
          </a-tooltip>
        </div>
        <div>
          <a-input-search v-model:value="cycle" @change="cycling" style="width: 100%;">
            <template #enterButton>
              <a-button style="cursor: default;">月</a-button>
            </template>
          </a-input-search>
        </div>
        <div v-if="textred"
             style="position: absolute;font-size: 12px;left: 0;bottom: -20px;color: red;">
          {{ textred }}
        </div>
      </div>

      <div class="mb-30">
        <div class="mb-5">
          <span style="color: red;">*</span>拆分后付款时间
        </div>
        <div>
          <a-input-group compact>
            <a-select v-model:value="bystages" style="width: 30%">
              <a-select-option :value="1">提前</a-select-option>
              <a-select-option :value="2">延后</a-select-option>
            </a-select>
            <a-input-number
                style="width: 40%"
                placeholder="请输入"
                v-model:value="times"
                :min="0"
            />
            <a-select v-model:value="statusbar" style="width: 30%">
              <a-select-option :value="1">自然日</a-select-option>
              <a-select-option :value="2">工作日</a-select-option>
            </a-select>
          </a-input-group>
        </div>
      </div>

      <a-button type="primary" @click="ordersplit" style="width: 100%;margin-bottom: 30px;" ghost>
        <template #icon>
          <plus-outlined/>
        </template>
        生成账单明细
      </a-button>

      <div v-if="Detailedreport.length > 0">
        <div class="fsb mb-15" style="height: 36px;line-height: 36px;">
          <span style="font-weight: 600;">拆分后账单明细报表</span>
          <div>
            <a-button v-if="!edites" @click="editclick">编辑</a-button>
            <a-button v-if="edites" @click="cancellation" style="margin-right: 10px;">取消
            </a-button>
            <a-button v-if="edites" @click="conserve"
                      :disabled="!(Number(Totalamount) == Number(Accumulatedamount))" type="primary"
                      ghost>保存
            </a-button>
          </div>
        </div>
        <div class="mb-15">
          <a-table
              :dataSource="EditList"
              :columns="columns"
              :pagination="false"
              rowKey="id"
          >
            <template #bodyCell="{ text, record, index, column }">
              <template v-if="column.key === 'interval'">
                <div style="height: 36px;line-height: 36px;">
                  <a-tag color="green">第{{ index + 1 }}期</a-tag>
                  {{ record.start_date }}~{{ record.end_date }}
                </div>
              </template>
              <template v-if="column.key === 'Payment_date'">
                <a-date-picker
                    v-if="edites"
                    v-model:value="record.pay_date"
                    :valueFormat="dateFormatStr"
                    :allowClear="false"
                    :disabled-date="disabledDate"
                    style="width: 120px"
                />
                <span v-else>{{ record.pay_date }}</span>
              </template>
              <template v-if="column.key === 'receivable'">
                <a-input v-if="edites" v-model:value="record.actual_retreat" @change="Editamount"
                         suffix="元"/>
                <span v-else>{{ record.actual_retreat }} 元</span>
              </template>
            </template>
          </a-table>
        </div>
        <div class="fsb">
          <div style="font-weight: 600;"> 总计</div>
          <div>
            <div>
              <span
                  style="font-weight: 600;margin-right: 5px;">费用应收总计：{{ Accumulatedamount }}元</span>
              <a-tooltip placement="topRight">
                <template #title>
                  <span> 拆分订单后的订单总金额不能小于和大于原始订单金额 </span>
                </template>
                <question-circle-outlined/>
              </a-tooltip>
            </div>
            <div v-if="Number(Totalamount) > Number(Accumulatedamount) " class="promptimg">当前比原始订单少
              ￥ {{ differential }}
            </div>
            <div v-if="Number(Totalamount) < Number(Accumulatedamount) " class="promptimg">当前比原始订单多
              ￥ {{ differential }}
            </div>
          </div>
        </div>
      </div>

    </div>

    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="onCancel">取消</a-button>
        <a-button type="primary"
                  :disabled="!splitApprove || !(EditList.length > 0) || !(Number(Totalamount) == Number(Accumulatedamount)) "
                  @click.prevent="onSubmit">保存&发起审批
        </a-button>
      </a-space>
    </div>

  </a-drawer>
</template>

<script>
import {
  computed,
  defineComponent,
  reactive,
  watch,
  ref,
  toRefs,
  createVNode,
} from "vue";
import request from "../../../../common/utils/request";
import store from "../../../../store";
import {Form, message, Modal} from "ant-design-vue";
import moment from "moment";
import {QuestionCircleOutlined, PlusOutlined} from "@ant-design/icons-vue";
import utils from "@/common/utils/utils";

const dateFormatStr = "YYYY-MM-DD";
import dayjs from 'dayjs';

export default defineComponent({
  name: "AddAdjust",
  components: {QuestionCircleOutlined, PlusOutlined},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    content: {
      type: Object,
      default: () => ({}),
    },
  },
  setup(props, context) {

    const state = reactive({
      cycle: '',
      times: '',
      bystages: 1,
      statusbar: 1,

      EditList: [],
      Detailedreport: [],
      edites: false,
      Totalamount: 0,
      Accumulatedamount: 0,
      differential: 0,
      textred: '',
      columns: [
        {
          title: "区间",
          key: "interval",
          dataIndex: "interval",
          width: 280,
        },
        {
          title: "付款日",
          key: "Payment_date",
          dataIndex: "Payment_date",
          width: 140,
        },
        {
          title: "应收",
          key: "receivable",
          dataIndex: "receivable",
          width: 140,
        }
      ],
      //提前审批
      splitApprove: false,
      splitis_admin: false,
      split_id: "",
      datapreams: {},
    });

    const disabledDate = (current) => {
      return current && current < dayjs().endOf('day');
    };

    const onCancel = () => {
      context.emit("cancel");
    };

    const ordersplit = () => {
      if (!state.cycle) {
        message.warning('请填写拆分周期');
        return
      }
      if (!state.times) {
        message.warning('请填写拆分后付款时间');
        return
      }
      state.datapreams = {
        id: props.content.id,
        pay_month: parseInt(state.cycle),
        pay_unit: state.bystages,
        day: parseInt(state.times),
        pay_unit1: state.statusbar,
      }
      request
          .post("/org", "/bill/order/split", state.datapreams)
          .then((res) => {
            state.Detailedreport = JSON.parse(JSON.stringify(res.list.detail))
            state.EditList = JSON.parse(JSON.stringify(res.list.detail))
            state.Totalamount = JSON.parse(JSON.stringify(res.list.total_amount))
            Editamount()
          })
    }

    const Editamount = () => {
      state.Accumulatedamount = 0
      for (let i = 0; i < state.EditList.length; i++) {
        state.Accumulatedamount += Number(state.EditList[i].actual_retreat)
      }
      state.Accumulatedamount = utils.toFixed2(state.Accumulatedamount)
      if (state.Totalamount > state.Accumulatedamount) {
        state.differential = utils.toFixed2(state.Totalamount - state.Accumulatedamount)
      }
      if (state.Totalamount < state.Accumulatedamount) {
        state.differential = utils.toFixed2(state.Accumulatedamount - state.Totalamount)
      }
    }

    const onSubmit = () => {
      if (state.edites) {
        message.warning('请先保存修改');
        return
      }
      if (!state.cycle) {
        message.warning('请填写拆分周期');
        return
      }
      if (!state.times) {
        message.warning('请填写拆分后付款时间');
        return
      }
      request
          .post("/org", "/bill/split/add", {
            detail: state.EditList,
            ...state.datapreams
          })
          .then((res) => {
            onCancel()
          })
    };

    const editclick = () => {
      state.edites = true
    }

    const cancellation = () => {
      state.edites = false
      state.differential = 0
      state.Accumulatedamount = state.Totalamount
      state.EditList = JSON.parse(JSON.stringify(state.Detailedreport))
    }

    const conserve = () => {
      state.edites = false
      state.Detailedreport = JSON.parse(JSON.stringify(state.EditList))
    }

    watch(
        () => state.bystages,
        (val) => {
          Cleardata()
        }
    );

    watch(
        () => state.times,
        (val) => {
          Cleardata()
        }
    );

    watch(
        () => state.statusbar,
        (val) => {
          Cleardata()
        }
    );

    const Cleardata = () => {
      state.EditList = []
      state.Detailedreport = []
      state.edites = false
      state.Totalamount = 0
      state.Accumulatedamount = 0
      state.differential = 0
      state.datapreams = {}
    }

    const cycling = () => {
      if (state.cycle && state.cycle > 0) {
        if (props.content.diff_month == state.cycle) {
          state.textred = '付款周期不能等于当前账单周期'
          message.warning(state.textred);
          return;
        } else {
          if (props.content.diff_month < state.cycle) {
            state.textred = '付款周期不能大于当前账单周期'
            message.warning(state.textred);
            return;
          }
          if (props.content.diff_month % state.cycle != 0) {
            console.log(props.content.diff_month, state.cycle, props.content.diff_month % state.cycle)
            state.textred = '当前账单周期不能被付款周期整除'
            message.warning(state.textred);
            return;
          } else {
            state.textred = ''
          }
        }
      } else {
        state.textred = '付款周期要大于0'
        return;
      }
      Cleardata()
    }

    const getadvance = () => {
      // 获取配置
      request
          .get("/org", "/approval/publish/process", {
            alias: "bill_split",
          })
          .then((res) => {
            state.splitApprove = res.info.process; //判断是否开启
            state.splitis_admin = res.info.is_admin; //判断是否有权限
            state.split_id = res.info.id;
          });
    };

    const goSetting = (id, index) => {
      state.apptype = index;
      if (window.__MICRO_APP_ENVIRONMENT__) {

        window.microApp.forceDispatch({
          type: "SetChildDrawerList",
          info: {
            props: {
              title: "审批设置",
              maskCloseable: true,
              visible: true,
              closable: true,
              width: 1200,
              bodyStyle: {padding: 0, background: '#f7f7f7', height: '100%'},
              destroyOnClose: true,
            },
            microId: "approval_ApprovalSettings",
            app: "workApproval",
            url: '/approval/ApprovalSettings',
            params: {
              id: id,
              isMainDrawer: true,
              closeApproval: () => {
                getadvance()
              }
            }
          },

        })
      }

    };

    const init = () => {
      getadvance()
    };

    init()

    return {
      ...toRefs(state),
      dateFormatStr,
      onCancel,
      onSubmit,
      editclick,
      cancellation,
      conserve,
      disabledDate,
      Editamount,
      cycling,
      ordersplit,
      getadvance,
      goSetting,
      Cleardata,
    };
  },
});
</script>
<style lang="less" scoped>
.prompt {
  background-color: #fffbe6;
  border: 1px solid #ffe58f;
  border-radius: 5px;
  padding: 8px 12px;
  font-size: 12px;
  margin-bottom: 20px;
}

.Billinformation {
  background-color: #f2f2f2;
  border-radius: 5px;
  padding: 8px 12px 3px 12px;
  color: #000000;
  margin-bottom: 20px;
}

.mb-15 {
  margin-bottom: 15px;
}

.mb-30 {
  margin-bottom: 30px;
}

.fsb {
  display: flex;
  justify-content: space-between;
}

.promptimg {
  background-color: #e8e8e8;
  color: red;
  padding: 2px 8px;
  font-size: 12px;
  margin-top: 2px;
}

</style>